package com.zhang.second.day04;

import com.zhang.second.utils.ClickEvent;
import com.zhang.second.utils.ClickSource;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: MapState状态变量：每来一条数据，输出一次这个用户对每个url的访问次数的HashMap
 * @author: zhang
 * @date: 2022/1/31 10:20
 */
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.username)
                .process(new KeyedProcessFunction<String, ClickEvent, String>() {
                    //key:url
                    //value:每个url的访问次数
                    private MapState<String, Long> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        mapState = getRuntimeContext().getMapState(
                                new MapStateDescriptor<String, Long>("url-state", Types.STRING, Types.LONG)
                        );
                    }

                    @Override
                    public void processElement(ClickEvent value, Context ctx, Collector<String> out) throws Exception {
                        if (!mapState.contains(value.url)) {
                            mapState.put(value.url, 1L);
                        } else {
                            mapState.put(value.url, mapState.get(value.url) + 1L);
                        }

                        StringBuilder result = new StringBuilder();
                        result.append(ctx.getCurrentKey() + "{\n");
                        for (String url : mapState.keys()) {
                            result.append("  " + url + ": " + mapState.get(url) + ";\n");
                        }
                        result.append("}\n");
                        out.collect(result.toString());
                    }
                })
                .print();

        env.execute();
    }
}
